
package com.google.libgdxpractice;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;

public class WorldRenderer {
	MyWorld world;
	OrthographicCamera cam;
	SpriteBatch batch;
	TextureRegion background;
	ImmediateModeRenderer renderer;

	public WorldRenderer (SpriteBatch batch, MyWorld world) {
		this.world = world;
		this.cam = new OrthographicCamera();
		this.cam.viewportWidth = Constants.WORLD_WIDTH;
		this.cam.viewportHeight = Constants.WORLD_HEIGHT;
		cam.position.set(Constants.WORLD_WIDTH/2, Constants.WORLD_HEIGHT/2, 0);
		this.batch = batch;
		renderer = new ImmediateModeRenderer();
	}


	public void render() {
        world.step(Gdx.graphics.getDeltaTime(), 3, 3);
        
		cam.update();
		batch.setProjectionMatrix(cam.combined);
		renderSky();
		renderGround();
		renderObjects();
	} 

	public void renderGround() {
		Vector2 position = world.groundBody.getPosition(); // that's the box's center position
		float angle = MathUtils.radiansToDegrees * world.groundBody.getAngle(); // the rotation angle around the center
		batch.disableBlending();
		batch.begin();
		batch.draw(Assets.groundRegion, 
				position.x, position.y, // the bottom left corner of the box, unrotated
				1f, 1f, // the rotation center relative to the bottom left corner of the box
				480, 32, // the width and height of the box
				1, 1, // the scale on the x- and y-axis
				angle);
		batch.end();
	}

	public void renderSky() {
		batch.disableBlending();
		batch.begin();
		batch.draw(Assets.skyRegion, cam.position.x - Constants.WORLD_WIDTH/2, cam.position.y - Constants.WORLD_HEIGHT/2, Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT);
		//batch.draw(Assets.groundRegion, cam.position.x - Constants.WORLD_WIDTH/2, cam.position.y - Constants.WORLD_HEIGHT/2, Constants.WORLD_WIDTH, Assets.groundRegion.getRegionHeight());
		batch.end();
	}

	public void renderObjects () {
		batch.enableBlending();
		batch.begin();
		renderBox();
		batch.end();	
	}

	private void renderBox() {
		Body box = world.boxBody;
		Vector2 position = box.getPosition(); // that's the box's center position
		float angle = MathUtils.radiansToDegrees * box.getAngle(); // the rotation angle around the center
		TextureRegion sprite = Assets.boxRegion;
		batch.draw(sprite, 
				position.x, position.y, // the bottom left corner of the box, unrotated
				1f, 1f, // the rotation center relative to the bottom left corner of the box
				sprite.getRegionWidth(), sprite.getRegionHeight(), // the width and height of the box
				1, 1, // the scale on the x- and y-axis
				angle);	}

}
